<?php

namespace app\data\controller\control;
use app\data\model\EnterStorehouseItemModel;
use app\data\model\EnterStorehouseModel;
use app\data\model\SendModel;
use app\data\model\StorehouseDataModel;
use app\data\model\StorehouseModel;
use think\admin\Controller;
use think\facade\Db;

/**
 * 入库管理
 * Class Goods
 * @package app\data\controller\shop
 */
class EnterStorehouse extends Controller
{
    /**
     * 绑定数据表
     * @var string
     */
    private $table = 'SnEnterStorehouse';

    /**
     * 最大分类等级
     * @var integer
     */
    protected $cateLevel;

    /**
     * 入库列表
     * @auth true
     * @menu true
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function index()
    {
        $this->title = '入库管理';
        $query = $this->_query($this->table);
        // 加载对应数据
        $this->type = $this->request->get('type', 'index');
        if ($this->type === 'index') $query->where(['deleted' => 0]);
        elseif ($this->type === 'recycle') $query->where(['deleted' => 1]);
        else $this->error("无法加载 {$this->type} 数据列表！");
        // $userInfo = session('user');
        // if($userInfo['id'] == 10000){
        //     $where = array();
        // }else{
        //     $where = array('admin_id'=>$userInfo['id']);
        // }
        // $query->where($where);
        // 列表排序并显示
        $query->like('title,admin_name');
        $query->equal('storehouse_id')->order('id desc')->page();
    }


    /**
     * 数据列表处理
     * @param array $data
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    protected function _page_filter(array &$data)
    {
        foreach ($data as $k=>$v){
            $data[$k]['storehouse_name'] = StorehouseModel::where('id',$v['storehouse_id'])->where('deleted',0)->value('name');
        }
        $this->storehouse_list = StorehouseModel::where('deleted',0)->select()->toArray();
    }

    /**
     * 添加
     * @auth true
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function add()
    {
        $this->mode = 'add';
        $this->title = '添加仓库数据';
        $this->_form($this->table, 'form');
    }

    /**
     * 编辑
     * @auth true
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function edit()
    {
        $this->mode = 'edit';
        $this->title = '编辑仓库数据';
        $this->_form($this->table, 'form');
    }



    /**
     * 表单数据处理
     * @param array $data
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    protected function _form_filter(array &$data)
    {
        $this->storehouse_list = StorehouseModel::where('deleted',0)->select()->toArray();
        if ($this->request->isGet()) {
            if(!isset($data['id'])){
                $this->lists = [];
            }else{
                $this->lists = EnterStorehouseItemModel::where('enter_id',$data['id'])->select()->toArray();
            }
        } elseif ($this->request->isPost()){
            if(!isset($data['material_code']) || count($data['material_code'])==0){$this->error('材料列表不可为空');}
            foreach ($data['material_num'] as $ks => $vs){
                if(!$vs){$this->error($data['material_name'][$ks].'('.$data['material_code'][$ks].')'.'数量不可为0');}
            }
            $admin_user = session('user');
            //开启事务
            Db::startTrans();
            try{
                if(!$data['id']){
                    //添加
                    $enter['title'] = date('Y年m月d日',time()).'入库物资';
                    $enter['admin_id'] = 0;
                    $enter['admin_name'] = '公共物资';
                    $enter['operate_id'] = $admin_user['id'];
                    $enter['operate_name'] = $admin_user['username'];
                    $enter['storehouse_id'] = $data['storehouse_id'];
                    $data['id'] = EnterStorehouseModel::insertGetId($enter);
                    if(!$data['id']) {throw new \Exception("服务器错误");}
                }
                //删除数据
                $resDel = EnterStorehouseItemModel::where('enter_id',$data['id'])->delete();
                if ($resDel === false) {throw new \Exception("服务器错误");}
                $cate_list = array();
                //组合数组
                foreach ($data['material_code'] as $k=>$v){
                    $cate_list[$k]['material_code'] = $v;
                    $cate_list[$k]['material_name'] = $data['material_name'][$k];
                    $cate_list[$k]['material_model'] = $data['material_model'][$k];
                    $cate_list[$k]['material_unit'] = $data['material_unit'][$k];
                    $cate_list[$k]['material_price'] = $data['material_price'][$k];
                    $cate_list[$k]['material_num'] = $data['material_num'][$k];
                    $cate_list[$k]['material_xjprice'] = sprintf("%01.2f", $data['material_price'][$k] * $data['material_num'][$k]);;
                    $cate_list[$k]['enter_id'] = $data['id'];
                    $cate_list[$k]['cate_id'] = $data['cate_id'][$k];
                    $cate_list[$k]['admin_id'] = 0;
                    $cate_list[$k]['admin_name'] = '公共物资';
                    $cate_list[$k]['storehouse_id'] = $data['storehouse_id'];
                }
                $res = EnterStorehouseItemModel::insertAll($cate_list);
                if(!$res) {throw new \Exception("服务器错误");}
                Db::commit();
            }catch(\Exception $e){
                // 回滚事务
                Db::rollback();
                // 获取提示信息
                $this->error($e->getMessage());die;
            }
        }
    }

    /**
     * 表单结果处理
     * @param boolean $result
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    protected function _form_result(bool $result)
    {
        if ($result && $this->request->isPost()) {
            $this->success('入库成功！');
        }
    }



    /**
     * 详情
     * @auth true
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function detail()
    {
        $id = input('id');
        $this->storehouseInfo = EnterStorehouseModel::where('id',$id)->find();
        $this->storehouse_name = StorehouseModel::where('id',$this->storehouseInfo['storehouse_id'])->value('name');
        $this->lists = EnterStorehouseItemModel::where('enter_id',$id)->select()->toArray();
        $this->fetch();
    }
    
    /**
     * 物资数量清空
     * @auth true
     */
    public function give_back_num()
    {
        $input = input('post.');
        $ControlClaimList = new EnterStorehouseItemModel();
        $info = $ControlClaimList->where('id',$input['id'])->find()->toArray();
        if(!$info){$this->error('数据不存在');}
        //开启事务
        Db::startTrans();
        try{
            //库存数据自减
            if(! Db::name('sn_storehouse_data')->where('material_code',$info['material_code'])->dec('material_num',$info['material_num'])->update()) throw new \Exception("服务器错误");
            $material_xjprice = sprintf("%01.2f", $info['material_price'] * $info['material_num']);
            if(! Db::name('sn_storehouse_data')->where('material_code',$info['material_code'])->dec('material_xjprice',$material_xjprice)->update()) throw new \Exception("服务器错误");
            $saveArr = array(
                'material_num'=>0,
                'material_xjprice'=>0,
            );
            $saveinfo = EnterStorehouseItemModel::where('id',$input['id'])->update($saveArr);
            if($saveinfo === false){return json(['code'=>500,'msg'=>'服务器繁忙']);}
            // 执行提交操作
            Db::commit();
        }catch(\Exception $e){
            // 回滚事务
            Db::rollback();
            // 获取提示信息
            $this->error($e->getMessage());die;
        }
        $this->success('数据更新成功');
    }

    /**
     * 确认入库
     * @auth true
     * @throws \think\db\exception\DbException
     */
    public function confirmReceipt()
    {
        $list = EnterStorehouseItemModel::where('enter_id',input('id'))->select()->toArray();
        //开启事务
        Db::startTrans();
        try{
            $saveData = ['status'=>1,'enter_time'=>date('Y-m-d H:i:s',time())];
            //子表数据更新
            $resz = Db::name('SnEnterStorehouseItem')->where('enter_id',input('id'))->update($saveData);
            if(!$resz) throw new \Exception("服务器错误");
            $res = Db::name('SnEnterStorehouse')->where('id',input('id'))->update($saveData);
            if(!$res) throw new \Exception("服务器错误");
            $StirehouseData = Db::name('SnStorehouseData');
            foreach ($list as &$v){
                //库存数量添加
                $where = array(
                    'material_code'=>$v['material_code'],
                );
                unset($v['id']);
                unset($v['enter_time']);
                if(!$StirehouseData->where($where)->count()){
                    if(!$StirehouseData->insert($v)) throw new \Exception("服务器错误");
                }else{
                    if(!$StirehouseData->where($where)->inc('material_num',$v['material_num'])->update()) throw new \Exception("服务器错误");
                }
            }
            Db::commit();
        }catch(\Exception $e){
            // 回滚事务$saveData
            Db::rollback();
            // 获取提示信息
            $this->error($e->getMessage());
        }
        $this->success('入库成功！');
    }

    /**
     * 删除
     * @auth true
     * @throws \think\db\exception\DbException
     */
    public function remove()
    {
        $this->_save($this->table, $this->_vali([
            'deleted.in:0,1'  => '状态值范围异常！',
            'deleted.require' => '状态值不能为空！',
        ]), 'id');
    }

}